<!--
    TODO 添加延迟输入触发模式
    TODO 添加高级查询模式
-->
<template>
	<div :class="searchClass"
	     class="search-control">
		<div class="search-box"
		     :class="searchBoxClass">
			<div class="search-icon"
			     @click="iconTrigger"
			     v-if="withSpread">
				<Icon type="ios-search"></Icon>
			</div>
			<div class="search-input-box">
				<input :disabled="fixedPanel && spread && withSpread"
				       v-model="key"
				       @input="$emit('input',key)"
				       v-on:keyup.enter="enterTrigger"
				       type="text"
				       :placeholder="placeholder"
				       class="search-input">
			</div>
			<div class="search-spread"
			     ref="spread"
			     @click.stop="spreadClick"
			     v-if="withSpread">
				<i class="ivu-icon ivu-icon-arrow-down-b"
				   v-show="!spread"></i>
				<i class="ivu-icon ivu-icon-arrow-up-b"
				   v-show="spread"></i>
			</div>
			<div class="search-icon"
			     @click="trigger"
			     v-if="!withSpread">
				<Icon type="ios-search"></Icon>
			</div>
		</div>
		<div class="action-right">
			<ActionPanelRight locate="right"
			                  :model="model.actions"
			                  v-if="model.actions"></ActionPanelRight>
		</div>
		<collapseTransition>
			<div class="search-form form-small"
			     ref="form_box"
			     v-if="withSpread && spreadLoad"
			     v-show="spread"
			     v-click-out="clickout">
				<SearchForm v-if="model"
				            @form-enter="formSubmit"
				            :class="{'search-require':formRequire?true:false}"
				            @validate="validateChange"
				            :module="moduleCode"
				            ref="form"
				            :autoCol="0"
				            :hasFullRow="false"
				            :validate="formRequire?true:false"
				            :col="formCol"
				            size="small"
				            :model="searchModel"
				            :impData="impData"></SearchForm>
				<div class="seach-btn-box pull-right">
					<Button type="text"
					        @click="closeForm">取消</Button>
					<Button type="ghost"
					        @click="clearData">重置</Button>
					<Button type="primary"
					        @click.stop="formSubmit"
					        :loading="fetching"
					        :disabled="formRequire?!enableSearch:false">搜索</Button>
				</div>
			</div>
		</collapseTransition>
	</div>
</template>

<script>
var searchCount = 0;
import ActionPanelRight from 'action/actionPanelRight';
import SearchForm from './form';
import $ from '@/common';
import Time from '@/common/time';
import collapseTransition from '@/element/collapseTransition';
import ClickOut from '@/directives/click-out';
export default {
	name: 'searchInput',
	props: {
		placeholder: {},
		small: {},
		model: {},
		data: {},
		fetching: {},
		filterData: {},
		hasSpread: {
			default: null,
		},
		formRequire: {},
		formCol: {},
		actionModel: {},
		fixedSearchPanel: {
			default: null,
		},
	},
	data() {
		return {
			defualtParam: {
				show_panel: true,
				fixed_panel: true,
			},
			key: null,
			//为ower表示，用于辅助locate rgiht action的判断
			fackOwner: true,
			withSpread: this.hasSpread,
			spread: false,
			isValidate: false,
			moduleCode: 0,
			enableSearch: true,
			spreadLoad: false,
		};
	},
	computed: {
		dev() {
			return $.dev;
		},
		searchClass() {
			return {
				'search-small': this.small,
				'search-fixed-panel': this.fixedPanel,
			};
		},
		searchBoxClass() {
			return {
				'search-has-spread': this.withSpread,
				'search-box-fixed-spread': this.fixedPanel && this.spread,
				'search-box-simple': !this.withSpread,
			};
		},
		actionParam() {
			var param = this.defualtParam;
			if (this.actionModel && this.actionModel.param) {
				param = $.setObj(this.actionModel.param, param);
			}
			return param;
		},
		//是否固定显示高级搜索栏
		fixedPanel() {
			if (this.fixedSearchPanel === null) {
				if (this.actionParam.fixed_panel !== false) this.spread = true;
				return this.actionParam.fixed_panel !== false;
			} else {
				return this.fixedSearchPanel;
			}
		},
		searchModel() {
			var model = $.copy(this.model);
			if (model && this.formRequire) {
				for (let field of model.fields) {
					if (this.formRequire[field.code]) {
						field.required = true;
					} else {
						field.required = false;
					}
				}
			}
			return model;
		},
		impData() {
			return { ...this.initSearchData, ...this.data };
		},
		//搜索初始数据 根据组件传输的默认过滤数据filterData 以及 field.param_def_value 组成
		initSearchData() {
			var data = { ...this.filterData };
			if (this.model && this.model.fields) {
				for (let i in this.model.fields) {
					let field = this.model.fields[i];
					if (field.param_def_value !== undefined) {
						var value = field.param_def_value;
						if (
							(field.type === 'date' || field.type === 'time' || field.type === 'timestamp') &&
							$.trim(field.param_def_value) === 'now()'
						) {
							var now = new Date();
							value = Time.toTs(`${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} 00:00:00`);
							if (field.param && field.param.range) {
								if (field.type === 'date') {
									data[field.code + '_start'] = value;
									data[field.code + '_end'] = value;
								} else {
									data[field.code + '_start'] = value;
									data[field.code + '_end'] = Time.toTs(
										`${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} 23:59:59`
									);
								}
							} else {
								data[field.code] = value;
							}
						} else {
							data[field.code] = value;
						}
					}
				}
			}
			return data;
		},
	},
	watch: {
		model: {
			immediate: true,
			handler() {
				this.spread = false;
				if (this.model && this.model.fields) {
					for (let i in this.model.fields) {
						if (this.model.fields[i].scope !== 'data') {
							this.withSpread = true;
							return;
						}
					}
					this.withSpread = false;
				} else {
					if (this.hasSpread !== null) {
						this.withSpread = this.hasSpread;
					} else {
						this.withSpread = false;
					}
				}
			},
		},
		spread: {
			immediate: true,
			handler(v) {
				if (v) this.spreadLoad = true;
			},
		},
	},
	created() {
		this.moduleCode = 'search_form_' + searchCount++;
		this.$owner = this.$parent;
	},
	methods: {
		trigger() {
			this.$emit('trigger', this.key);
		},
		redraw() {
			this.$refs.form && this.$refs.form.redraw();
		},
		//固定的高级查询模式，点击搜索icon时为收起高级查询，而不是搜索
		iconTrigger() {
			if (this.spread && this.fixedPanel) {
				this.spreadClick();
			} else {
				if (!this.fetching) {
					this.trigger();
				}
			}
		},
		enterTrigger() {
			if (!this.fetching) {
				this.trigger();
			}
		},
		validateChange(v) {
			this.enableSearch = v;
		},
		clearData() {
			this.$refs.form.setData(this.initSearchData);
		},
		spreadClick() {
			if (!this.spread) {
				this.spread = true;
			} else {
				this.closeForm();
			}
		},
		clickout() {
			if (!this.fixedPanel) {
				this.closeForm();
			}
		},
		closeForm() {
			this.spread = false;
		},
		formData() {
			return this.$refs.form.formData;
		},
		setFormData(data) {
			this.$refs.form.setData(data);
			this.formSubmit();
		},
		formTrigger() {
			this.$emit('formTrigger', this.formData());
			if (!this.fixedPanel) {
				this.closeForm();
			}
		},
		formSubmit() {
			if (this.formRequire) {
				this.$refs.form.doValidate();
				this.$nextTick(() => {
					if (!this.enableSearch && !this.isValidate) {
						this.$Message.error('表单验证失败!');
					} else {
						this.formTrigger();
					}
					this.isValidate = true;
				});
			} else {
				this.formTrigger();
			}
		},
	},
	directives: {
		ClickOut,
	},
	components: {
		SearchForm,
		ActionPanelRight,
		collapseTransition,
	},
};
</script>

<style lang="less">
.node-panel .search-control {
	align-self: flex-end;
	position: relative;
}

.search-control {
	.seach-btn-box {
		padding-right: 1px;
		.ivu-btn {
			margin-left: 6px;
		}
	}
	&.search-fixed-panel {
		.search-form {
			position: static;
			width: 100%;
			clear: both;
			box-shadow: none;
			border: none;
			margin-bottom: 28px;
			padding: 0px 0px 16px;
			border-top: 1px solid #dddee1;
			padding-top: 8px;
		}
	}
	.search-require {
		.field-control {
			margin-bottom: 14px;
		}
	}
	.search-form {
		position: absolute;
		z-index: 4;
		width: 60vw;
		top: 40px;
		right: 0px;
		background: #fff;
		padding: 16px;
		border: 1px solid #dddee1;
		box-shadow: 0 0 2px rgba(149, 149, 149, 0.47);
	}
	.search-box {
		transition: all 0.2s;
		display: table;
		position: relative;
		float: right;
		padding-bottom: 10px;
		width: 230px;
		&.search-box-fixed-spread {
			width: 52px;
			.search-input-box {
				> .search-input {
					padding: 0;
				}
			}
			&:hover {
				.search-icon,
				.search-spread {
					background: #f8f8f9;
				}
			}
		}
		&.search-box-simple {
			width: 200px;
			.search-input-box {
				> .search-input {
					padding-right: 8px;
					padding-left: 8px;
				}
			}
		}
		.search-input-box {
			overflow: hidden;
		}
		&.search-has-spread {
			.search-input {
				border-radius: 0;
			}
			.search-icon {
				border-radius: 4px 0 0 4px;
				border-right-width: 0;
				border-left-width: 1px;
			}
		}
		.search-input {
			display: table-cell;
			width: 100%;
			height: 32px;
			line-height: 1.5;
			padding: 4px 7px;
			font-size: 12px;
			border: 1px solid #dddee1;
			border-radius: 4px 0 0 4px;
			color: #495060;
			background-color: #fff;
			background-image: none;
			position: relative;
			cursor: text;
			transition: border 0.2s ease-in-out, background 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
		}
		.search-icon,
		.search-spread {
			font-size: inherit;
			display: table-cell;
			font-weight: 400;
			cursor: pointer;
			line-height: 1;
			color: #495060;
			text-align: center;
			background-color: #eee;
			border: 1px solid #dddee1;
			&:hover {
				background: #f8f8f9;
			}
		}
		.search-icon {
			padding: 4px 12px;
			border-radius: 0 4px 4px 0;
			border-left-width: 0;
			> i {
				font-size: 14px;
				line-height: -13px;
				top: 2px;
				position: relative;
			}
		}
		.search-spread {
			padding: 4px 4px;
			border-radius: 0 4px 4px 0;
			border-left-width: 0;
			&.focus {
				outline-color: -webkit-focus-ring-color;
				outline-style: auto;
				outline-width: 5px;
				outline-offset: -2px;
			}
		}
	}
}
</style>
